var app = getApp();
Page(Object.assign({}, {
    data: {
        activeIndex: 0,
        fromqcode: true, //true 扫码
        siteroot: app.siteInfo.siteroot.replace('app/index.php', ''),
        uniacid: app.siteInfo.uniacid,
        isIPX: app.globalData.isIPX,
        page: {
            isend: false,
            doing: false,
            doo: 'shopinfo',
            pdata: {
                op: 'goodlist',
                page: 2,
                shopid: 0,
                search: '',
                sorttwo: 0,
                stype: 1,
                shopsort: 0,
            },
            waitf: 0,
            nodataf: 0,
        },
        datalist: [],
        ising: false,
        slidedata: [],
        state: {
            slidedata: [],
            currentIndex: 0,
            currentData: {},
            status: "hide",
            anmiate: 0
        },
        shop: {},
        morecard: false,
        tabtype: 0,
        sort: [],
        SharePopupshow: false,
        pagedata: [],
        pagetype: 0,
        isautoload: false,
        bar: {},
        actoil: -1,
        actgun: -1,
    },
    onLoad: function (options) {
        var self = this;
        if (app.globalData.scene == 1011) {
            this.setData({
                fromqcode: true
            })
            wx.hideHomeButton()
        }
        if (options.scene) {
            var list = options.scene.split('_');
            options.id = list[0] ? list[0] : 0;
            options.zfid = list[1] ? list[1] : 0;
        }
        var id = options.id ? options.id : (options.scene ? options.scene : 0);
        app.globalData.shopid = id;

        var is_takeout = options.is_takeout ? options.is_takeout : 0;

        var zfid = options.zfid ? options.zfid : '';
        var shareid = options.shareid ? options.shareid : '';
        self.setData({
            'page.pdata.shopid': id,
            'page.pdata.is_takeout': is_takeout,
            options: options,
        });
        app.com.getLocation(self, function (loc) {
            app.com.auth(function () {

                var postdata = {
                    op: 'info',
                    id: id,
                    is_takeout: options.is_takeout ? options.is_takeout : 0,  // 是否是只展示外卖的商品
                    zfid: zfid,
                    lat: loc.latitude,
                    lng: loc.longitude,
                    shareid: shareid,
                    isposter: options.scene || options.isposter * 1 == 1 ? 1 : 0,
                    isinit: self.data.shop.id ? 1 : 0,
                }

                app.com.http('shopinfo_v1', 'POST', postdata, 0, false, '', '', function (res) {
                    if (res.data && !res.data.errno) {
                        // res.data.data.shop.lat = loc.latitude;
                        // res.data.data.shop.lng = loc.longitude;
                        // 初始化页面获取购物车信息
                        self.getCartShop()
                        self.setData({
                            inited: true,
                            shop: res.data.data.shop,
                            lat: loc.latitude,
                            lng: loc.longitude,
                        })
                        app.globalData.shopunav = res.data.data.params.shopunav;
                        setTimeout(function () {
                            self.setData({
                                datalist: res.data.data.list ? res.data.data.list : [],
                                pagedata: res.data.data.page ? res.data.data.page : [],
                                sharedata: res.data.data.sharedata,
                                params: res.data.data.params,
                                userinfo: res.data.data.userinfo,
                                bar: res.data.data.bar,
                                allcard: res.data.data.allcard ? res.data.data.allcard : [],
                                fendian: res.data.data.fendian ? res.data.data.fendian : [],
                                slidedata: res.data.data.slide ? res.data.data.slide : [],
                                sort: res.data.data.sort ? res.data.data.sort : [],
                                footimg: res.data.data.footimg ? res.data.data.footimg : [],
                            });
                            self.data.pagetype = res.data.data.pagetype;

                            wx.setNavigationBarTitle({
                                title: res.data.data.shop.name
                            });

                            if (self.data.pagetype == 0) {
                                if (res.data.data.shop.content) {

                                    var octoparse = require('../resource/wxParse/html2json2.js');
                                    var transData = octoparse.parse(res.data.data.shop.content);
                                    self.setData({
                                        nodes: transData,
                                    })
                                }
                            } else {
                                for (var i = 0; i < res.data.data.page.length; i++) {
                                    var thisd = res.data.data.page[i];
                                    if (thisd.name == 'downget') {
                                        self.onReachBottom();
                                        return false;
                                    }
                                }
                            }
                        }, 5);

                    } else {
                        app.com.alert(res.data.message, function () {
                            app.com.backPage(options.zfid);
                        });
                    }
                });
            });
        })
    },
    onPullDownRefresh: function () {
        if (this.data.isdown) return false;
        this.onLoad(this.data.options);
        this.data.isdown = false;

        var pdownget = this.selectComponent('#pdownget');
        if (pdownget) pdownget.reset('down');

        wx.stopPullDownRefresh();
    },
    toggleDetail() {
        this.setData({
            showDetail: !this.data.showDetail,
        })
    },
    onShareAppMessage: function () {
        var self = this;
        return {
            title: self.data.sharedata.title,
            path: self.data.sharedata.path,
            imageUrl: self.data.sharedata.img,
        }
    },
    onReachBottom: function () {
        var self = this;
        if (self.data.shop.auth.idxstyle == 3) {
            var pdownget = this.selectComponent('#pdownget');
            if (pdownget) pdownget.load();
        } else {
            if (self.data.ising) return false;
            app.com.getPage(self, self.data.page, 20, function (res) {
                self.setData({
                    datalist: self.data.datalist.concat(res.data.data.list)
                });
            });
        }
    },
    onPageScroll: function (e) {
        var self = this;
        if (e.scrollTop > 50 && !self.data.scrollstatus1) {
            self.setData({
                topstatus: true
            });
            self.data.scrollstatus1 = true;
            self.data.scrollstatus2 = false;
        }
        if (e.scrollTop <= 50 && !self.data.scrollstatus2) {
            self.setData({
                topstatus: false
            });
            self.data.scrollstatus1 = false;
            self.data.scrollstatus2 = true;
        }
    },
    tab(e) {
        this.setData({
            tabtype: e.detail.index
        })
    },
    changesort(e) {
        var self = this;

        this.setData({
            activeIndex: e.currentTarget.dataset.id,
        })
        if (self.data.ising) return false;
        self.data.ising = true;

        self.setData({
            'page.pdata.isselfsort': self.data.shop.isselfsort,
            'page.pdata.sorttwo': e.currentTarget.dataset.id,
            'page.pdata.page': 1,
            'page.isend': false,
            'page.waitf': 0,
            'page.nodataf': 0,
            'page.pdata.is_takeout' : self.options.is_takeout ? self.options.is_takeout : 0,
        });
        app.com.getPage(self, self.data.page, 20, function (res) {

            self.setData({
                datalist: res.data.data.list,
            });
        });
        self.data.ising = false;
    },
    takecard(e) {
        var self = this;
        var postdata = {
            op: 'takecard',
            id: e.currentTarget.dataset.id,
        };
        app.com.http('card', 'POST', postdata, 0, true, '', '', function (res) {

            if (!res.data.errno && res.data) {
                for (var i = 0; i < self.data.allcard.length; i++) {
                    if (self.data.allcard[i].id == postdata.id) {
                        self.setData({
                            ['allcard[' + i + '].istaked']: 1,
                        });
                        return false;
                    }
                }
                app.com.toast(res.data.message);
            } else if (res.data.errno == 2) {

                app.com.confirm(res.data.message, function () {
                    var tourl = '/zofui_sales/ucard/buycard';
                    wx.navigateTo({
                        url: tourl
                    });
                }, false, '取消', '购买会员');

            } else if (res.data.errno == 5) {
                wx.navigateTo({
                    url: '/zofui_sales/card/info?id=' + postdata.id
                });
            } else {
                app.com.toast(res.data.message);
            }

        });
    },
    comfirm() {
        var self = this;

        if (self.data.ising) return false;
        self.data.ising = true;

        self.setData({
            'page.pdata.search': self.data.page.pdata.search,
            'page.pdata.page': 1,
            'page.isend': false,
            'page.waitf': 0,
            'page.nodataf': 0
        });

        app.com.getPage(self, self.data.page, 20, function (res) {
            self.setData({
                datalist: res.data.data.list,
            });
        });

        self.data.ising = false;
    },
    searchinput(e) {
        var self = this;
        self.setData({
            'page.pdata.search': e.detail.value,
        });
    },
    close() {
        this.setData({
            'page.pdata.search': '',
        });
        this.comfirm();
    },
    couponShow() {
        this.setData({
            morecard: !this.data.morecard
        })
    },
    openShareArea: function (e) {
        var self = this;
        self.setData({
            SharePopupshow: !self.data.SharePopupshow
        }, function () {
            if (self.data.SharePopupshow && !self.data.posterurl) {
                self.getPoster();
            }
        })
        setTimeout(function () {
            self.setData({
                shareVisible: self.data.SharePopupshow ? 'visible' : ''
            })
        }, 300)
    },
    getPoster() {
        var self = this;
        app.com.http('poster', 'POST', {
            op: 'shop',
            sid: self.data.shop.id,
            path: self.data.sharedata.path
        }, 0, true, '', '', function (res) {
            if (!res.data.errno && res.data) {
                self.setData({
                    posterurl: res.data.data.url
                });
                app.com.alert('可长按图片保存到本地相册和发给好友！', function () {
                    wx.previewImage({
                        urls: [res.data.data.url]
                    })
                });
            } else {
                app.com.toast(res.data.message);
            }
        });
    },
    saveposter() {
        var self = this;
        wx.downloadFile({
            url: self.data.posterurl,
            success: function (res) {
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success(res) {
                        app.com.toast('已保存到本地相册');
                    },
                    fail(res) {
                        app.com.toast('保存失败');
                    }
                })
            },
            fail: function (res) {
                app.com.toast('下载文件失败');
            }
        })
    },
    // handleClick
    handleClick(e) {
        console.log('判斷收藏還是點讚', e.detail);
        switch (e.detail.type) {
            case 'collect':
                this.collect()
                break;
            case 'zan':
                this.zan()
                break;
            case 'tel':
                this.callphone(e)
                break;
            case 'more':
                console.log('滚动');
                wx.pageScrollTo({
                    selector: '.goods',
                    duration: 300
                })
                this.setData({
                    tabtype: 1
                })
                break;
            default:
                break;
        }
    },
    collect() {
        var self = this;
        var postdata = {
            op: 'collect',
            id: self.data.shop.id,
        }
        app.com.http('shopinfo_v1', 'POST', postdata, 0, true, '', '', function (res) {
            app.com.toast(res.data.message);
            self.setData({
                ['shop.iscollected']: res.data.errno
            })
        });
    },
    zan() {
        var self = this;
        var postdata = {
            op: 'zan',
            id: self.data.shop.id,
        }
        app.com.http('shopinfo_v1', 'POST', postdata, 0, true, '', '', function (res) {
            app.com.toast(res.data.message);
            self.setData({
                ['shop.iscollected']: res.data.errno
            })
        });
    },
    selectoil(e) {
        var i = e.currentTarget.dataset.i;
        this.setData({
            actoil: i,
        })
    },
    payoil(e) {
        var self = this;
        if (self.data.actoil < 0) {
            app.com.toast('还没选择油品');
            return false;
        }
        var postdata = {
            op: 'topayoil',
            oilid: self.data.shop.oillist ? self.data.shop.oillist[self.data.actoil].id : '',
            gunid: self.data.shop.gunlist && self.data.actgun >= 0 ? self.data.shop.gunlist[self.data.actgun].id : '',
        }
        app.com.http('shopinfo_v1', 'POST', postdata, 0, true, '', '', function (res) {
            if (!res.data.errno && res.data) {
                wx.navigateTo({
                    url: '/zofui_sales/shop/payoil'
                });
            } else {
                app.com.toast(res.data.message);
            }
        });
    },
    location: function (e) {
        app.com.location(e);
    },
    otherapp: function (e) {
        app.com.otherapp(e);
    },
    navigateto: function (e) {
        app.com.navigateto(e, this.data.tid);
    },
    redirectto: function (e) {
        app.com.redirectto(e, this.data.tid);
    },
    callphone: function (e) {
        app.com.callphone(e);
    },
    showimages: function (e) {
        app.com.showimages(e);
    },
    FormIdsubmit: function (e) {

    },
    footNavigate(e) {
        var url = e.currentTarget.dataset.url;
        wx.switchTab({
            url: url
        })
    },
    showJoin(e) {
        var self = this;
        self.setData({
            Joinanimation: !self.data.Joinanimation,
        })
    },
    // 显示购物车列表
    showCart() {
        this.setData({
            isShowCart: true
        });
        wx.stopPullDownRefresh()
    },
    // 隐藏购物车列表
    hideCart() {
        this.setData({
            isShowCart: false
        });
        wx.startPullDownRefresh()
    },
    // 获取购物车信息
    getCartShop() {
        console.log('---');
        var self = this
        var options = this.options
        var shopid = options.id;
        var zfid = '';
        app.com.auth(function (user) {
            app.com.getLocation(self, function (loc) {
                var postdata = {
                    op: 'info',
                    lat: loc.latitude,
                    lng: loc.longitude,
                    zfid: zfid,
                    shopid: shopid,
                }
                app.com.http('cart', 'POST', postdata, 0, false, '', '', function (res) {
                    if (!res.data.errno && res.data) {
                        self.setData({
                            'cart.goodlist': res.data.data.goodlist,
                        });
                    }
                });
            })
        });
    },
    // 结算
    countit() {
        var self = this;
        var arr = [];
        var k = 0,
            l = 0;
        for (var i = 0; i < self.data.cart.goodlist.length; i++) {
            var item = self.data.cart.goodlist[i].list;
            for (var j = 0; j < item.length; j++) {
                var ina = {
                    cid: item[j].cid,
                    num: item[j].num * 1
                };
                arr.push(ina);
                k = i;
                l = j;
            }
        }

        if (arr.length < 1) {
            app.com.toast('还没选择');
            return false;
        } else if (arr.length == 1) {
            var item = self.data.cart.goodlist[k].list[l];
            wx.setStorageSync('zfssbuy', {
                'gid': item.id,
                type: 0,
                mapid: item.ruleid ? item.ruleid : '',
                mapname: item.rulename ? item.rulename : '',
                num: item.num
            });

        } else {
            wx.setStorageSync('zfssbuy', {
                arr: arr,
                type: 'cart'
            });
        }
        console.log(this.data.shop);

        var tourl = '/zofui_sales/order/confirm';
        wx.navigateTo({ url: tourl});

        // if(this.data.shop.type){
        //     this.createorder()
        // }else {
        //     var tourl = '/zofui_sales/order/confirm';
        // wx.navigateTo({
        //   url: tourl
        // });
        // }
    },
    /**
     * 创建order
     */
    createorder() {

        var self = this;

        app.com.getLocation(self, function (loc) {
            app.com.auth(function (user) {
                var cache = wx.getStorageSync('zfssbuy');
                if (!cache || cache == "") {
                    //wx.navigateBack();
                } else {
                    var postdata = {
                        op: 'info',
                        gid: cache.gid ? cache.gid : 0,
                        cid: cache.cid ? cache.cid : 0,
                        num: cache.num ? cache.num : 1,
                        groupid: cache.groupid ? cache.groupid : 0,
                        cartlist: cache.arr ? JSON.stringify(cache.arr) : [],
                        type: cache.type,
                        mapid: cache.mapid,
                        groupmem: cache.groupmem ? cache.groupmem : '',
                        addcart: 1,
                        lat: (loc.latitude ? loc.latitude : 0),
                        lng: (loc.longitude ? loc.longitude : 0),
                        ischangeadd: 0,
                    };
                    self.data.lat = postdata.lat;
                    self.data.lng = postdata.lng;

                    app.com.http('confirmv1_v1', 'POST', postdata, 0, false, '', '', function (res) {
                        if (!res.data.errno && res.data) {
                            let orderdata = {
                                isusejifen: 0,
                                jifendis: 0,
                                params: res.data.data.params,
                                goodlist: res.data.data.goodlist ? res.data.data.goodlist : [],
                                userinfo: res.data.data.userinfo,
                                name: res.data.data.params.ordername,
                                tel: '123',
                                pcard: res.data.data.params.orderpcard,
                                num: 1,
                                buytype: cache.type,
                                mapid: cache.mapid,
                                groupmem: cache.groupmem ? cache.groupmem : 0,
                                mapname: cache.mapname ? cache.mapname : '',
                                groupid: cache.groupid ? cache.groupid : 0,
                                liveid: cache.liveid ? cache.liveid : '',
                                cid: cache.cid ? cache.cid : 0,
                                inited: true,
                                allcard: res.data.data.allcard ? res.data.data.allcard : [],
                                taketype: res.data.data.params.taketype,
                                paytype: res.data.data.params.paytype,
                                myredbag: res.data.data.myredbag ? res.data.data.myredbag : false,
                                form: res.data.data.form ? res.data.data.form : false,
                                ctaddress: res.data.data.userinfo.ctyaddress ? res.data.data.userinfo.ctyaddress : '',
                                ctyarea: res.data.data.myaddress ? res.data.data.myaddress.ctyarea : '',
                            }
                            if (postdata.ischangeadd == 0) {
                                orderdata['aname'] = res.data.data.myaddress ? res.data.data.myaddress.name : ''
                                orderdata['address'] = res.data.data.myaddress ? res.data.data.myaddress.address : ''
                                orderdata['lat'] = res.data.data.myaddress ? res.data.data.myaddress.lat : self.data.lat
                                orderdata['lng'] = res.data.data.myaddress ? res.data.data.myaddress.lng : self.data.lng
                            }
                            self.confirm(orderdata)
                        } else if (res.data.errno == 2) {
                            app.com.alert('你还有未支付的订单，请先支付', function () {
                                wx.setStorageSync('zfssbuy', '');
                                var tourl = '/zofui_sales/order/orderinfo?id=' + res.data.data.orderid;
                                wx.navigateTo({
                                    url: tourl
                                });
                            });
                        } else if (res.data.errno == 3) {
                            app.com.confirm(res.data.message, function () {
                                wx.setStorageSync('zfssbuy', '');
                                var tourl = '/zofui_sales/ucard/buycard';
                                wx.navigateTo({
                                    url: tourl
                                });
                            }, function () {
                                wx.navigateBack();
                            }, '取消', '购买会员');
                        } else {
                            app.com.alert(res.data.message, function () {
                                wx.navigateBack();
                            });
                        }
                    })
                }
            });
        })

    },

    confirm(orderdata) {
        var self = this;
        var subform = [];
        var goodlist = [];
        for (var i = 0; i < orderdata.goodlist.length; i++) {
            var item = orderdata.goodlist[i];
            var into = {
                cardid: item.cardid,
                yhmcode: item.yhmcode,
                list: []
            };
            for (var j = 0; j < item.list.length; j++) {
                into.list.push({
                    id: item.list[j].id,
                    gid: item.list[j].gid,
                    num: item.list[j].num,
                    redid: item.list[j].redbagid,
                    yydate: item.list[j].yydate ? item.list[j].yydate : '',
                    yytime: item.list[j].yytime ? item.list[j].yytime : '',
                    toshopid: item.list[j].toshopid ? item.list[j].toshopid : '',
                    oname: item.list[j].oname ? item.list[j].oname : '',
                });
            }
            goodlist.push(into);
        }

        var pidarr = wx.getStorageSync('tclist');

        var postdata = {
            op: 'pay',
            taketype: orderdata.taketype,
            paytype: orderdata.paytype,
            name: orderdata.name,
            tel: orderdata.tel,
            pcard: orderdata.pcard,
            mess: orderdata.mess,
            num: orderdata.num,
            buytype: orderdata.buytype,
            groupid: orderdata.groupid,
            cid: orderdata.cid,
            aname: orderdata.aname,
            atel: '',
            province: orderdata.province ? orderdata.province : '',
            city: orderdata.city ? orderdata.city : '',
            country: orderdata.country ? orderdata.country : '',
            address: orderdata.address,
            ctyarea: orderdata.ctyarea ? orderdata.ctyarea : '',
            liveid: orderdata.liveid ? orderdata.liveid : '',
            cardid: orderdata.cardid,
            isusejifen: orderdata.isusejifen ? orderdata.isusejifen : 0,
            jifendis: orderdata.jifendis > 0 ? orderdata.jifendis : 0,
            ctaddress: orderdata.ctaddress ? orderdata.ctaddress : '',
            groupmem: orderdata.groupmem ? orderdata.groupmem : 0,
            mapid: orderdata.mapid ? orderdata.mapid : '',
            addcart: 1, // 新版的
            goodlist: goodlist ? JSON.stringify(goodlist) : [],
            subform: subform ? JSON.stringify(subform) : 0,
            lat: orderdata.lat,
            lng: orderdata.lng,
            pidarr: pidarr ? JSON.stringify(pidarr) : [],
            paynumber: orderdata.paynumber ? orderdata.paynumber : '',
            paycid: orderdata.paycid ? orderdata.paycid : '',
        };

        if (orderdata.payed) return false;
        orderdata.payed = true;

        app.com.http('confirmv1_v1', 'POST', postdata, 0, true, '', '', function (res) {
            orderdata.payed = false;
            if (!res.data.errno && res.data) {
                wx.setStorageSync('zfssbuy', '');
                if (res.data.data.payed == 1) {
                    self.paysuc(res.data.data, orderdata.buytype);
                    if (res.data.data.channel) {
                        app.com.sendGo(res.data.data.gomess, res.data.data.channel);
                    }
                } else {
                    self.setData({ // 防止返回商品
                        isback: false,
                    })
                    wx.requestPayment({
                        'appId': res.data.data.appId,
                        'timeStamp': res.data.data.timeStamp,
                        'nonceStr': res.data.data.nonceStr,
                        'package': res.data.data.package,
                        'signType': 'MD5',
                        'paySign': res.data.data.paySign,
                        'success': function (payres) {
                            if (payres.errMsg == 'requestPayment:ok') {
                                self.paysuc(res.data.data, orderdata.buytype);
                                if (res.data.data.channel) {
                                    app.com.sendGo(res.data.data.gomess, res.data.data.channel);
                                }
                            }
                        },
                        'fail': function (payres) {
                            var tip = orderdata.params.fontsty == 33 ? '请尽快提交' : '请尽快支付';

                            app.com.toast(tip, 'fail', function () {
                                var tourl = '/zofui_sales/order/orderinfo?id=' + res.data.data.orderid;
                                if (orderdata.buytype == 'cart') {
                                    tourl = '/zofui_sales/order/orderlist?dealid' + res.data.data.orderid;
                                    if (orderdata.params.shopnav * 1 == 1) {
                                        tourl += '?shopid=' + orderdata.goodlist[0].shopid;
                                    }
                                }
                                wx.navigateTo({
                                    url: tourl,
                                    complete: function () {
                                        self.setData({
                                            isback: true,
                                        })
                                    }
                                });

                            });
                        }
                    });
                }
            } else {
                app.com.alert(res.data.message);
            }
        });

    },
}))